//
//  AppDelegate.m
//  BaChat
//
//  Created by 刘洋 on 16/6/13.
//  Copyright © 2016年 刘洋. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "LoginAndRegisterViewController.h"
#import "NewFriendModel.h"


#import <MAMapKit/MAMapKit.h>
#import <AMapSearchKit/AMapSearchKit.h>
#import <AMapFoundationKit/AMapFoundationKit.h>




@interface AppDelegate ()<EMCallManagerDelegate,IChatManagerDelegate>

@property(nonatomic,retain)NSMutableDictionary *friendNewDic;
@property(nonatomic,retain)NSMutableArray *friendNewList;
@property(nonatomic,retain)BaseTabBarController *myTabBar;



@end

@implementation AppDelegate

-(void)dealloc{
    [_myTabBar release];
    [_friendNewDic release];
    [_friendNewList release];
    [super dealloc];
}

+(NSMutableDictionary *)shareFriendDic{
    static NSMutableDictionary *dic = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dic = [[NSMutableDictionary alloc]init];
    });
    return dic;
}


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    self.friendNewList = [NSMutableArray array];
   self.friendNewDic = [NSMutableDictionary dictionary];

    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    [_window release];
    

    
    // 设置chatManager代理
    // 写个nil 默认代理会在主线程调用
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    
    
    //注册环信SDK
   //registerSDKWithAppKey 注册的AppKey
   //apnsCertName: 推送证书名（不需要加后缀）
    [[EaseMob sharedInstance] registerSDKWithAppKey:@"liuyang2211#bachat" apnsCertName:@""];
    
    
    //必须写这句话才能自动登录
    [[EaseMob sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
    
    
    //判断是否是自动登录状态(只有登录后才能改变为自动登录状态);
    if ([[EaseMob sharedInstance].chatManager isAutoLoginEnabled]) {
        NSLog(@"自动登录了");
        self.myTabBar = [[BaseTabBarController alloc]init];
        self.window.rootViewController = self.myTabBar;
        [_myTabBar release];
        
    }else{
        NSLog(@"不是自动登录状态");
        LoginAndRegisterViewController *loginVC = [[LoginAndRegisterViewController alloc]init];
        self.window.rootViewController = loginVC;
        [loginVC release];
        
        
        
        
    }
    
    
    
    
    
    return YES;
}

#pragma mark -- 重连方法
//将要发起自动重连操作是发送该回调
-(void)willAutoReconnect{
    
    
}

//自动重连操作完成后的回调
-(void)didAutoReconnectFinishedWithError:(NSError *)error{
    
    
}

#pragma mark -- 监听加好友请求
-(void)didReceiveBuddyRequest:(NSString *)username message:(NSString *)message{

  [[AppDelegate shareFriendDic] setObject:message forKey:username];


//通知改变新加好友的未读消息
        [[NSNotificationCenter defaultCenter]postNotificationName:@"contactsBadgeValue" object:[NSString stringWithFormat:@"%ld",[AppDelegate shareFriendDic].count]];
    
     NSLog(@"%@",[AppDelegate shareFriendDic]);
  
    
    }
    

  
    

    


- (void)didFetchedBuddyList:(NSArray *)buddyList
                      error:(EMError *)error{
    
    
    if (!error) {
 //       NSLog(@"")
        NSMutableArray *listArr = [NSMutableArray arrayWithArray:buddyList];
        NSLog(@"%@",listArr);
        
    }
    
}







#pragma mark -- 被其他设备顶掉
-(void)didLoginFromOtherDevice{
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"该帐户已在其他应用登录" preferredStyle:UIAlertControllerStyleAlert];

    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
     
        [[EaseMob sharedInstance].chatManager setIsAutoLoginEnabled:NO];
        
       [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:YES completion:^(NSDictionary *info, EMError *error) {
           
           if (!error) {
               NSLog(@"退出成功");
               LoginAndRegisterViewController *loginVC = [[LoginAndRegisterViewController alloc]init];
               self.window.rootViewController = loginVC;
               [loginVC release];
            
               
           }
           
            
        } onQueue:dispatch_get_main_queue()];
        
        [[AppDelegate shareFriendDic] removeAllObjects];
        
    }]];
    
    [self.window.rootViewController presentViewController:alert animated:YES completion:^{
        
        
    }];
    
  
   
    
    
}



- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

#pragma mark -- App进入后台
- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    [[EaseMob sharedInstance] applicationDidEnterBackground:application];
    
    
}

#pragma mark -- App将要从后台返回
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

    [[EaseMob sharedInstance]applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

#pragma mark -- 申请处理时间
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    
     [[EaseMob sharedInstance] applicationWillTerminate:application];
    
    
}

@end
